<?php
class Faq_Pro_Admin extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
        modules::run('auth/auth/validate_login',$this->router->fetch_module());
        $this->_layout = 'admin_ui/layout/main';
        $this->_view_data['url'] = FAQ_PRO_ADMIN_BASE_URL;
    }

    function browse($para1=DEFAULT_LANGUAGE, $para2=1)
    {
        $options            = array('lang'=>switch_language($para1),'page'=>$para2);
        $options            = array_merge($options, $this->_get_data_from_filter());
        $this->phpsession->save('faq_professionals_lang', $options['lang']);

        $total_row          = $this->faq_professionals_model->get_faq_professionals_count($options);
        $total_pages        = (int)($total_row / FAQ_ADMIN_POST_PER_PAGE);
        if ($total_pages * FAQ_ADMIN_POST_PER_PAGE < $total_row) $total_pages++;
        if ((int)$options['page'] > $total_pages) $options['page'] = $total_pages;

        $options['offset']  = $options['page'] <= DEFAULT_PAGE ? DEFAULT_OFFSET : ((int)$options['page'] - 1) * FAQ_ADMIN_POST_PER_PAGE;
        $options['limit']   = FAQ_ADMIN_POST_PER_PAGE;

        $config = prepare_pagination(
            array(
                'total_rows'    => $total_row,
                'per_page'      => $options['limit'],
                'offset'        => $options['offset'],
                'js_function'   => 'change_page_admin'
            )
        );
        $this->pagination->initialize($config);
        $options['faq_professionals'] = $this->faq_professionals_model->get_faq_professionals($options);
        $options['lang_combobox'] = $this->utility_model->get_lang_combo(array('lang' => $options['lang'], 'extra' => 'onchange="javascript:change_lang();" class="btn"'));
        $options['post_uri'] = 'faq_pro_admin';
        $options['total_rows'] = $total_row;
        $options['total_pages'] = $total_pages;
        $options['page_links'] = $this->pagination->create_ajax_links();
        
        if($options['lang'] <> DEFAULT_LANGUAGE){
            $options['uri'] = FAQ_PRO_ADMIN_BASE_URL . '/' . $options['lang'];
        }else{
            $options['uri'] = FAQ_PRO_ADMIN_BASE_URL;
        }
        
        if(isset($options['error']) || isset($options['succeed']) || isset($options['warning'])) 
            $options['options'] = $options;

        // Chuan bi du lieu chinh de hien thi
        $this->_view_data['main_content'] = $this->load->view('pro/list',$options, TRUE);
        
        // Chuan bi cac the META
        $this->_view_data['title'] = 'Quản lý danh sách chuyên gia' . DEFAULT_TITLE_SUFFIX;
        // Tra lai view du lieu cho nguoi su dung
        $this->load->view($this->_layout, $this->_view_data);
    }
    
    /**
     * Lấy dữ liệu từ filter
     * @return string
     */
    private function _get_data_from_filter()
    {
        $options = array();

        if ( $this->is_postback())
        {
            $options['search'] = $this->db->escape_str($this->input->post('search', TRUE));
            $this->phpsession->save('faq_pro_search_options', $options);
            //search with lang
            $options['lang'] = $this->input->post('lang');
        }
        else
        {
            $temp_options = $this->phpsession->get('faq_pro_search_options');
            if (is_array($temp_options))
            {
                $options['search'] = $temp_options['search'];
            }
            else
            {
                $options['search'] = '';
            }
        }
        return $options;
    }

    function add()
    {
        $options = array();
        
        if($this->is_postback())
        {
            if (!$this->_do_add())
                $options['error'] = validation_errors();
            if (isset($options['error'])) $options['options']   = $options;
        }
        $options += $this->_get_add_form_data();
        // Chuan bi du lieu chinh de hien thi
        $this->_view_data['main_content'] = $this->load->view('pro/form', $options, TRUE);
        // Chuan bi cac the META
        $this->_view_data['title'] = 'Thêm chuyên gia' . DEFAULT_TITLE_SUFFIX;
        
        // Tra lai view du lieu cho nguoi su dung
        $this->load->view($this->_layout, $this->_view_data);
    }

    private function _get_add_form_data()
    {
        $options                  = array();
        $options['title']         = my_trim($this->input->post('title'));
        $options['summary']       = my_trim($this->input->post('summary'));
        $options['thumb']         = $this->input->post('thumb');
        $options['content']       = $this->input->post('content');
        if($this->is_postback())
        {
            $options['created_date']  = $this->input->post('created_date');
            $options['lang_combobox'] = $this->utility_model->get_lang_combo(array('lang' => $this->input->post('lang', TRUE), 'extra' => 'onchange="javascript:get_categories_by_lang();" class="btn"'));
        }
        else
        {
            $options['created_date']  = date('d-m-Y');
            $options['lang_combobox'] = $this->utility_model->get_lang_combo(array('lang' => $this->phpsession->get('faq_professionals_lang'), 'extra' => 'onchange="javascript:get_categories_by_lang();" class="btn"'));
        }

        $options['scripts']       = $this->_get_scripts();
        $options['header']        = 'Thêm chuyên gia';
        $options['button_name']   = 'Lưu dữ liệu';
        $options['submit_uri']    = FAQ_PRO_ADMIN_BASE_URL.'/add';

        return $options;
    }

    private function _do_add()
    {
        $this->form_validation->set_rules('title', 'Tên', 'trim|required|xss_clean|max_length[255]');
        $this->form_validation->set_rules('thumb', 'Hình ảnh', 'trim|required|xss_clean');
        $this->form_validation->set_rules('summary', 'Mô tả', 'trim|required|xss_clean|max_length[1000]');
//        $this->form_validation->set_rules('content', 'Nội dung', 'required');
//        $this->form_validation->set_rules('security_code', 'Mã an toàn', 'trim|required|xss_clean|matches_value[' . $this->phpsession->get('captcha') . ']');

        if ($this->form_validation->run())
        {
            $post_data = $this->_get_posted_data();
            $post_data['creator'] = $this->phpsession->get('user_id');
            $position_add = $this->faq_professionals_model->position_to_add_faq_pro();
            $post_data['position'] = $position_add;
            $post_data['created_date']  = date('Y-m-d H:i:s');
            $insert_id = $this->faq_professionals_model->insert($post_data);
            redirect(FAQ_PRO_ADMIN_BASE_URL . '/' . $post_data['lang']);
        }
        return FALSE;
    }

    private function _get_posted_data()
    {
        $content = str_replace('&lt;', '<', $this->input->post('content'));
        $content = str_replace('&gt;', '>', $content);
        $post_data = array(
            'title'               => my_trim($this->input->post('title', TRUE)),
            'summary'             => my_trim($this->input->post('summary', TRUE)),
            'content'             => $content,
            'thumbnail'           => cut_domain_from_url($this->input->post('thumb')),
            'lang'                => $this->input->post('lang', TRUE),
            'updated_date'        => date('Y-m-d H:i:s'),
            'status'              => STATUS_ACTIVE,
        );

        $post_data['editor'] = $this->phpsession->get('user_id');
        return $post_data;
    }

    function edit()
    {
        $options = array();
        
        if(!$this->is_postback()) redirect(FAQ_PRO_ADMIN_BASE_URL);

        if ($this->is_postback() && !$this->input->post('from_list'))
        {
            if (!$this->_do_edit())
                $options['error'] = validation_errors();
            if (isset($options['error'])) $options['options']   = $options;
        }

        $options += $this->_get_edit_form_data();

        // Chuan bi du lieu chinh de hien thi
        $this->_view_data['main_content'] = $this->load->view('pro/form', $options, TRUE);
        // Chuan bi cac the META
        $this->_view_data['title'] = 'Sửa chuyên gia' . DEFAULT_TITLE_SUFFIX;
        
        // Tra lai view du lieu cho nguoi su dung
        $this->load->view($this->_layout, $this->_view_data);
    }
    /**
     * Chuẩn bị dữ liệu cho form sửa
     * @return type
     */
    private function _get_edit_form_data()
    {
        $id = $this->input->post('id');
        if($this->input->post('from_list'))
        {
            $faq_pro           = $this->faq_professionals_model->get_faq_professionals(array('id' => $id));
            $id             = $faq_pro->id;
            $title          = $faq_pro->title;
            $summary        = $faq_pro->summary;
            $content        = $faq_pro->content;
            $thumb          = $faq_pro->thumbnail;
            $lang           = $faq_pro->lang;
        }

        // khi submit
        else
        {
            $id             = $id;
            $title          = my_trim($this->input->post('title', TRUE));
            $summary        = my_trim($this->input->post('summary', TRUE));
            $content        = $this->input->post('content', TRUE);
            $thumb          = $this->input->post('thumb');
            $lang           = $this->input->post('lang', TRUE);
        }

        $options                  = array();
        $options['id']            = $id;
        $options['title']         = $title;
        $options['summary']       = $summary;
        $options['thumb']         = $thumb;
        $options['content']       = $content;
        $options['lang_combobox'] = $this->utility_model->get_lang_combo(array('lang' => $lang, 'extra' => 'onchange="javascript:get_categories_by_lang();" class="btn"'));
        $options['header']        = 'Sửa chuyên gia';
        $options['button_name']   = 'Sửa chuyên gia';
        $options['submit_uri']    = FAQ_PRO_ADMIN_BASE_URL.'/edit';
        $options['scripts']       = $this->_get_scripts();

        return $options;
    }
    /**
     *  sửa trong DB nếu Validate OK
     * @return type
     */
    private function _do_edit()
    {
        $this->form_validation->set_rules('title', 'Tên', 'trim|required|xss_clean|max_length[255]');
        $this->form_validation->set_rules('thumb', 'Hình ảnh', 'trim|required|xss_clean');
        $this->form_validation->set_rules('summary', 'Mô tả', 'trim|required|xss_clean|max_length[1000]');
//        $this->form_validation->set_rules('content', 'Nội dung', 'required');
        if ($this->form_validation->run())
        {
            $post_data = $this->_get_posted_data();
            $post_data['id'] = $this->input->post('id');
            $position_edit = $this->faq_professionals_model->position_to_edit_faq_pro(array('id'=>$this->input->post('id')));
            $post_data['position'] = $position_edit;
            $this->faq_professionals_model->update($post_data);
            redirect(FAQ_PRO_ADMIN_BASE_URL . '/' . $post_data['lang']);
        }
        return FALSE;
    }

    /**
     * Xóa tin
     */
    public function delete()
    {
        $options = array();
        if($this->is_postback())
        {
            $id = $this->input->post('id');
            $this->faq_professionals_model->delete($id);
            $options['warning'] = 'Đã xóa thành công';
        }
        $lang = $this->phpsession->get('faq_professionals_lang');
        redirect(FAQ_PRO_ADMIN_BASE_URL . '/' . $lang);
    }

//    private function _get_scripts()
//    {
//        $scripts = '<script type="text/javascript" src="/plugins/tiny_mce/tiny_mce.js?v=20111006"></script>';
//        $scripts .= '<script language="javascript" type="text/javascript" src="/plugins/tiny_mce/plugins/imagemanager/js/mcimagemanager.js?v=20111006"></script>';
//        $scripts .= '<script type="text/javascript">enable_advanced_wysiwyg("wysiwyg");</script>';
//        return $scripts;
//    }
    
    private function _get_scripts()
    {
        $scripts = '<script type="text/javascript" src="/plugins/tinymce/tinymce.min.js?v=4.1.7"></script>';
        $scripts .= '<link rel="stylesheet" type="text/css" href="/plugins/fancybox/source/jquery.fancybox.css" media="screen" />';
        $scripts .= '<script type="text/javascript" src="/plugins/fancybox/source/jquery.fancybox.pack.js"></script>';
        $scripts .= '<script type="text/javascript">$(".iframe-btn").fancybox({"width":900,"height":500,"type":"iframe","autoScale":false});</script>';
        $scripts .= '<style type=text/css>.fancybox-inner {height:500px !important;}</style>';
        $scripts .= '<script type="text/javascript">enable_tiny_mce();</script>';
        return $scripts;
    }
    
    function change_status()
    {
        $id = $this->input->post('id');
        $data = $this->faq_professionals_model->get_faq_professionals(array('id' => $id));
        $status = $data->status == STATUS_ACTIVE ? STATUS_INACTIVE : STATUS_ACTIVE;
        $this->faq_professionals_model->update(array('id'=>$id,'status'=>$status));
    }
    
    public function up()
    {
        $id = $this->input->post('id');
        $this->faq_professionals_model->item_to_sort_faq_pro(array('id' => $id));
        $lang = $this->phpsession->get('faq_professionals_lang');
        redirect(FAQ_PRO_ADMIN_BASE_URL . '/' . $lang);
    }
    
}